package com.pan.show.record.impl;

import com.pan.domain.Dot;
import com.pan.show.record.Record;
import com.pan.utils.ApplicationConfig;

import javax.swing.*;
import java.text.SimpleDateFormat;
import java.util.concurrent.atomic.AtomicInteger;

public class FrameAppendRecord implements Record<String> {

    private JFrame frame;
    private JTextArea textArea;
    private JScrollPane scrollPane;

    private AtomicInteger flag = new AtomicInteger(1);

    private SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    private void casFlag(int expectedValue,int newValue){
        while (flag.compareAndSet(expectedValue,newValue)){
            try {
                Thread.sleep(10);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
    }
    private void takeFlag(){casFlag(1,0);}
    private void returnFlag(){casFlag(0,1);}

    public FrameAppendRecord() {
        frame = new JFrame("Record");
        frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
        textArea = new JTextArea(14,36);
        textArea.setEditable(false);
        textArea.setFont(ApplicationConfig.INSTANCE.getFont());
        scrollPane = new JScrollPane(textArea);
        frame.add(scrollPane);
        frame.pack();
    }

    @Override
    public void setContent(String content) {
        takeFlag();
        String formatDate = simpleDateFormat.format(System.currentTimeMillis());
        textArea.append("---------------------------\n");
        textArea.append(formatDate+" : \n");
        textArea.append(content+"\n");
        returnFlag();
    }

    @Override
    public void display() {
        frame.setVisible(true);
    }

    @Override
    public void close() {
    }


    public static void main(String[] args) {

        FrameAppendRecord frameAppendRecord = new FrameAppendRecord();
        frameAppendRecord.display();
        for (int i = 0; i < 10; i++) {
            Dot dot = new Dot((int) (Math.random()*2000), (int) (Math.random()*1500));
            frameAppendRecord.setContent(dot.toString());
        }
    }
}
